package com.weilele.leisure.time

import android.app.PendingIntent
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.drawable.GradientDrawable
import android.net.Uri
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.view.setPadding
import androidx.lifecycle.Observer
import com.google.android.exoplayer2.offline.Download
import com.weilele.leisure.time.bean.db.HistoryVideoBean
import com.weilele.leisure.time.ui.module.video_cache.VideoCacheActivity
import com.weilele.leisure.time.ui.player.TransformingMediaHelper
import com.weilele.mvvm.app
import com.weilele.mvvm.base.livedata.StatusData
import com.weilele.mvvm.utils.activity.*
import com.weilele.mvvm.utils.formJsonString
import com.weilele.mvvm.utils.toJsonString
import com.yizisu.playerlibrary.databinding.PlayerLibRcvCacheItemBinding
import com.yizisu.playerlibrary.service.download.PlayerDownload
import com.yizisu.playerlibrary.view.video_view.helper.IPlayerConfig
import com.yizisu.playerlibrary.view.video_view.helper.playerLibDebug
import com.yizisu.playerlibrary.view.video_view.view.PlayerCacheView


/**
 * 初始化视频缓存参数
 */
const val VIDEO_ID_OTHER_DOWNLOAD = -1
const val VIDEO_ID_SD_CARD = -2
fun initCacheVideoParams() {
    playerLibDebug = true
    PlayerDownload.updateNotificationUi = {
        val intent = PendingIntent.getActivity(
            app, 100,
            Intent(app, VideoCacheActivity::class.java).apply {
                flags = Intent.FLAG_ACTIVITY_NEW_TASK
            }, PendingIntent.FLAG_UPDATE_CURRENT
        )
        val title = "正在缓存${it.count()}个视频"
        PlayerDownload.NotificationUi(android.R.drawable.stat_sys_download, title, intent)
    }

    /**
     * 拦截视频库下载逻辑
     */
    PlayerDownload.onInterceptCacheClickListener =
        object : Function2<PlayerCacheView, IPlayerConfig, Boolean> {
            override fun invoke(
                playerCacheView: PlayerCacheView,
                iPlayerConfig: IPlayerConfig
            ): Boolean {
                playerCacheView.invisible()
                playerCacheView.canDownload = false
                val model =
                    iPlayerConfig.player?.getCurrentModel() ?: return true
                val contentId =
                    model.mediaItem?.playbackProperties?.uri?.toString()
                        ?: return true
                val videoTitle = model.getTitle()?.toString()
                "下载任务《${videoTitle}》已添加".toast()
                PlayerDownload.startOrResumeDownload(
                    contentId, Uri.parse(contentId),
                    buildBlock = {
                        it.setData(
                            HistoryVideoBean().apply {
                                videoId = VIDEO_ID_OTHER_DOWNLOAD
                                title = "其他下载"
                                playTitle = videoTitle
                                playUrl = contentId
                            }.toJsonString()
                                .toByteArray()
                        )
                    }
                )
                return true
            }
        }
    /**
     * 设置绑定holder监听
     */
    PlayerDownload.onCacheVideoBindHolderListener =
        object : Function3<PlayerLibRcvCacheItemBinding, Download, Boolean, Unit> {
            override fun invoke(
                binding: PlayerLibRcvCacheItemBinding,
                download: Download,
                isBind: Boolean
            ) {
                if (isBind) {
                    binding.tvProgress.setPadding(0)
                    val lp = binding.tvProgress.layoutParams as LinearLayout.LayoutParams
                    lp.height = 1.dp
                    binding.tvProgress.layoutParams = lp
                    binding.tvProgress.progressDrawable =
                        getResDrawable(R.drawable.progress_bar_theme)
                    binding.tvName.setTextColor(getResColor(R.color.colorAppText))
                    binding.tvDelete.setTextColor(getResColor(R.color.colorAppText))
                    binding.tvDes.setTextColor(getResColor(R.color.colorAppTextSecondary))
                    binding.tvStatus.setTextColor(getResColor(R.color.colorAccent))
                    binding.tvDes.setPadding(0, 4.dp, 0, 8.dp)
                    binding.tvStatus.setPadding(8.dp, 8.dp, 8.dp, 8.dp)
                    binding.tvDelete.setPadding(8.dp, 8.dp, 8.dp, 8.dp)
                    binding.tvStatus.background = GradientDrawable().apply {
                        cornerRadius = 4f.dp
                        color = ColorStateList.valueOf(getResColor(R.color.colorPrimary))
                    }
                    binding.tvDelete.background = GradientDrawable().apply {
                        cornerRadius = 4f.dp
                        color = ColorStateList.valueOf(getResColor(R.color.colorPrimary))
                    }
                    binding.tvName.textSize = 14f
                    binding.tvDes.textSize = 11f
                    binding.tvStatus.textSize = 11f
                    binding.tvDelete.textSize = 11f
                    val bean = String(download.request.data).formJsonString<HistoryVideoBean>()
                    if (!bean.playTitle.isNullOrBlank()) {
                        binding.tvName.text = bean.playTitle
                    }
                }
                //region 下载完成，可以数据转换
                if (download.state == Download.STATE_COMPLETED) {
                    binding.tvStatus.text = "转MP4"
                    observerTransforming(binding.tvStatus, download)
                    binding.tvStatus.onClick {
                        if (TransformingMediaHelper.startTransformer(
                                it,
                                download,
                                binding.tvName.text.toString()
                            )
                        ) {
                            observerTransforming(binding.tvStatus, download)
                        }
                    }
                }
                //endregion
            }
        }
}

/**
 * 处理转mp4时，监听器的转化和移除
 */
private fun observerTransforming(view: TextView, download: Download) {
    TransformingMediaHelper.checkTaskData(download)
    val liveData = TransformingMediaHelper.checkTaskData(download)
    if (liveData != null) {
        view.isEnabled = false
        val observer = Observer<StatusData<TransformingMediaHelper.TransformingInfo>> {
            view.text = it?.data?.message
        }
        if (view.tag is Observer<*>) {
            liveData.removeObserver(view.tag as Observer<StatusData<TransformingMediaHelper.TransformingInfo>>)
        }
        view.tag = observer
        liveData.observeForever(observer)
        view.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
            override fun onViewAttachedToWindow(v: View?) {

            }
            override fun onViewDetachedFromWindow(v: View?) {
                liveData.removeObserver(observer)
            }
        })
    }
}